<script setup lang='ts' name="trade-in-apply">
import { exportTradeInfo, getTradeInApplyPage, queryRegionList } from '@fl/api/xf-api/xf-manage'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { cloneDeep, result } from 'lodash-es'
import { reactive, ref } from 'vue'

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    totalResult: 0,
})

function handlePageChange(page) {
    tablePage.currentPage = page.currentPage
    tablePage.pageSize = page.pageSize
    queryTableData()
}

const loading = ref(false)

type queryForm = {
    name?: number | string
    phone?: string
    region?: string
    createTime: []
}

const form = reactive<queryForm>({
    name: '',
    phone: '',
    region: '',
    createTime: [],
})

function resetForm() {
    form.name = ''
    form.phone = ''
    form.region = ''
    form.createTime = []
    queryTableData()
}

const policyTableData = ref([])

function timeChange(val) {
    if (!val) {
        form.createTime = []
    }
    tablePage.currentPage = 1
}

async function queryTableData() {
    const { code, data, msg, total } = await getTradeInApplyPage({
        name: form.name ? form.name : undefined,
        phone: form.phone ? form.phone : undefined,
        region: form.region ? form.region : undefined,
        createTimeBegin: form.createTime?.length > 0 ? `${form.createTime?.[0]} 00:00:00` : undefined,
        createTimeEnd: form.createTime?.length > 0 ? `${form.createTime?.[1]} 23:59:59` : undefined,
    }, {
        pageNum: tablePage.currentPage,
        pageSize: tablePage.pageSize,
    })
    if (code === 200) {
        const records = data || []
        policyTableData.value = []
        policyTableData.value = records
        tablePage.totalResult = total
    }
    else {
        ElMessage.error(msg)
    }
    loading.value = false
}

const xTable1 = ref(null)

const districtTypes = ref([])
function getRegions() {
    queryRegionList().then((res: any) => {
        if (res.code === 200) {
            if (res.data) {
                districtTypes.value = res.data
            }
        }
    }).catch((error) => {
        ElMessage.error(error.msg)
    })
}

function changeArea(val) {
    if (val) {
        const areaItem = districtTypes.value.find((item) => {
            return item?.id === val
        })
        addForm.areaName = areaItem.name
    }
}

function deleteRow(row) {
    ElMessageBox.confirm(
        `是否确认删除此记录`,
        '系统提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
        },
    )
        .then(() => {
            doSearch()
        })
}

async function doExport() {
    const params = {
        name: form.name ? form.name : undefined,
        phone: form.phone ? form.phone : undefined,
        region: form.region ? form.region : undefined,
        createTimeBegin: form.createTime.length > 0 ? `${form.createTime?.[0]} 00:00:00` : undefined,
        createTimeEnd: form.createTime.length > 0 ? `${form.createTime?.[1]} 23:59:59` : undefined,
    }
    const result = await exportTradeInfo(params)
    const fileName = `以旧换新意向${dayjs().format('YYYYMMDD')}`
    const blob = new Blob([result], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const href = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.style.display = 'none'
    a.href = href // 指定下载链接
    a.download = fileName // 指定下载文件名
    a.click()
    URL.revokeObjectURL(a.href) // 释放URL对象
}

function doSearch() {
    queryTableData()
}

onMounted(() => {
    queryTableData()
    getRegions()
})

onUnmounted(() => {
    policyTableData.value = []
})
</script>

<template>
    <el-card style="padding-bottom:60px">
        <div style="height: 560px;padding-bottom:20px">
            <el-form :inline="true"
                     :model="form"
                     label-width="100"
                     class="query_form"
            >
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="申请人"
                                      prop="name"
                        >
                            <el-input v-model="form.name"
                                      clearable
                                      class="inline-input w-50"
                                      placeholder="请输入政策名称"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="联系方式"
                                      prop="phone"
                        >
                            <el-input v-model="form.phone"
                                      clearable
                                      class="inline-input w-50"
                                      placeholder="请输入联系方式"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="区域">
                            <el-row style="width:100% !important;">
                                <el-col>
                                    <el-select v-model="form.region"
                                               class="m-2"
                                               placeholder="请选择区域"
                                               clearable
                                    >
                                        <el-option v-for="item in districtTypes"
                                                   :key="item.areaCode"
                                                   :value="item.areaName"
                                                   :label="item.areaName"
                                        />
                                    </el-select>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="提交时间"
                                      prop="createTime"
                        >
                            <el-date-picker v-model="form.createTime"
                                            type="daterange"
                                            range-separator="至"
                                            start-placeholder="开始日期"
                                            end-placeholder="结束日期"
                                            value-format="YYYY-MM-DD"
                                            format="YYYY-MM-DD"
                                            @change="timeChange"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8"
                            :offset="1"
                    >
                        <el-button type="primary"
                                   @click="doSearch()"
                        >
                            搜索
                        </el-button>

                        <el-button @click="resetForm">
                            重置
                        </el-button>

                        <el-button type="primary"
                                   @click="doExport()"
                        >
                            导出
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>

            <el-scrollbar>
                <vxe-table ref="xTable1"
                           :data="policyTableData"
                           :height="480"
                           :show-header="true"
                           stripe
                           :border="true"
                           :loading="loading"
                           :row-config="{ isHover: true }"
                           :tooltip-config="{ zIndex: 9999 }"
                >
                    <vxe-column field="name"
                                title="申请人姓名"
                                min-width="100"
                                show-overflow="tooltip"
                    />

                    <vxe-column field="phone"
                                title="联系方式"
                                min-width="120"
                                show-overflow="tooltip"
                    />

                    <vxe-column field="region"
                                title="区划"
                                min-width="100"
                                show-overflow="tooltip"
                    />

                    <vxe-column field="addr"
                                title="楼盘或小区名称(旧房)"
                                min-width="100"
                                show-overflow="tooltip"
                    />

                    <vxe-column field="memo1"
                                title="房屋坐落地址(旧房)"
                                min-width="150"
                                show-overflow="tooltip"
                    />

                    <vxe-column field="floorArea"
                                title="建筑面积(旧房)㎡"
                                min-width="140"
                                show-overflow="tooltip"
                    />

                    <vxe-column field="newRegion"
                                title="意向购房区划(新房)"
                                min-width="100"
                                show-overflow="tooltip"
                    />

                    <vxe-column field="preferredLayout"
                                title="期望户型(新房)"
                                min-width="120"
                                show-overflow="tooltip"
                    />

                    <vxe-column title="面积需求(新房)㎡"
                                field="preferredArea"
                                width="140"
                    />

                    <vxe-column field="targetTotal"
                                title="新房总价预算区间(万元)"
                                width="120"
                                align="center"
                                show-overflow="tooltip"
                    />

                    <vxe-column title="置换时间表"
                                field="memo2"
                                show-overflow="tooltip"
                                width="150"
                                align="center"
                    />

                    <vxe-column title="意向楼盘(新房)"
                                field="preferredProject"
                                show-overflow="tooltip"
                                width="150"
                                align="center"
                    />

                    <vxe-column title="提交时间"
                                field="createTime"
                                show-overflow="tooltip"
                                width="150"
                                align="center"
                    />
                </vxe-table>

                <vxe-pager :loading="loading"
                           :current-page="tablePage.currentPage"
                           :page-size="tablePage.pageSize"
                           :total="tablePage.totalResult"
                           :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                           @page-change="handlePageChange"
                />
            </el-scrollbar>
        </div>
    </el-card>
</template>

<style lang="scss" scoped>
.query_form {
    :deep(.el-form-item) {
        width: 100%;
    }
    :deep(.el-form-item__content) {
        width: 100%;
    }
    :deep(.el-radio) {
        margin-right: 12px;
    }
}
:deep() {
    --vxe-primary-color: #da0004;
    --vxe-loading-color: #da0004;
}

:deep(.vxe-table--render-default .vxe-body--row.row--stripe) {
    background-color: #fff !important;
}

.operate-icon {
    display: flex;
    align-items: center;
    .el-icon {
        font-size: 24px;
        margin-left: 10px;
        cursor: pointer;
        color: #da0004;
    }
}

:deep(.vxe-pager--btn-wrapper .vxe-pager--num-btn.is--active) {
    color: #fff;
}
</style>
